package demo.c1;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * Row query
 *
 * @author chisheng
 */
@AllArgsConstructor
public class RowQuery {

    /* @Override
     * public void run() {
     *    // if Runnable is passed during Thread contruction,
     *    // Runnable's run method is executed.
     *    if (target != null) {
     *        target.run();
     *    }
     * } */

    /**
     * A connection (session) with a specific database
     */
    private final Connection conn;

    /**
     * Data query and wrap to T instance by row handler
     *
     * @param handler row handler
     * @param sql     SQL statement
     * @param params  SQL paramters
     * @param <T>     T type
     * @return T instance
     */
    @SneakyThrows
    public <T> T query(RowHandler<T> handler, String sql, Object... params) {
        final PreparedStatement pstmt = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            pstmt.setObject(i, params[i]);
        }

        return handler.handle(pstmt.executeQuery());
    }

}
